package hikari.gui.guicomponents.draggable_tree;

import hikari.utils.L;

import javax.swing.*;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.DefaultTreeModel;
import javax.swing.tree.TreeNode;
import javax.swing.tree.TreePath;
import java.util.Enumeration;

/**
 * @author Dmitry
 */
public class DraggableTree extends JTree {

    private NodeMoveTransferHandler handler;
    protected DefaultTreeModel model;

    public DraggableTree(TreeNode root) {
        super(root);
        init();
    }

    public DraggableTree(String rootNodeCaption) {
        super(new DefaultMutableTreeNode(rootNodeCaption));
        init();
    }

    private void init() {
        setRootVisible(true);
        setShowsRootHandles(true);
        setEditable(true);
        handler = new NodeMoveTransferHandler();
        setTransferHandler(handler);
        setDropTarget(new TreeDropTarget(handler));
        setDragEnabled(true);
        model = (DefaultTreeModel) getModel();
    }

    public void setOnChangeParentEvent(DraggableTreeChangeParentEvent event) {
        handler.setOnChangeParentEvent(event);
    }

    public DefaultMutableTreeNode searchNode(Object innerData) {
        if(innerData==null){
            return null;
        }
        DefaultMutableTreeNode node = null;
        Enumeration e = ((DefaultMutableTreeNode) model.getRoot()).breadthFirstEnumeration();
        while (e.hasMoreElements()) {
            node = (DefaultMutableTreeNode) e.nextElement();
            if (innerData.equals(node.getUserObject())) {
                return node;
            }
        }

        return null;
    }

    public TreePath getPathToNode(TreeNode node) {
        TreeNode[] nodes = model.getPathToRoot(node);
        TreePath path = new TreePath(nodes);
        return path;
    }

    public void selectNode(TreeNode node) {
        TreePath path = getPathToNode(node);
        if (path != null) {
            setSelectionPath(path);
        }
    }
}
